<template>
  <div id='content' class="content">
    <div id="scenery-list" v-loading="tableLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(34, 52, 87, 0.6)">
      <!-- 景点收藏列表... -->
      <div :class="{ scenery_item: true, with_cover: item.img != null }" v-for="item in tableCollect" :key="item.FID">
        <div class="title" @click="toDetail(item)">{{ item.name }}</div>
        <div class="abstract">{{ item.intro }}</div>
        <div class="info">
          <span class="user-name">{{ item.leval }}</span>
          <div class="footer-divider"></div>
          <span class="view">
            <i class="el-icon-position" />
            {{ item.city }}
          </span>
          <span>
            {{ item.region }}
          </span>
          <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
          <el-popover placement="right" width="150" v-model="item.popVisible">
            <el-button size="mini" type="danger" @click="deleteSceneryCollect(item)"><i class="el-icon-delete"></i>取消收藏</el-button>
            <i class="el-icon-more" slot="reference"></i>
          </el-popover>
        </div>
        <div class="cover" v-if="item.img != null">
          <el-image style="width: 114px; height: 90px" :src="item.img" :fit="'cover'" />
        </div>
      </div>
    </div>
    <el-pagination background layout="prev, pager, next" :page-size="pageSize" :total="totalSize" :current-page="pageNum" hide-on-single-page
      @current-change="handleCurrentChange">
    </el-pagination>
    <el-dialog title="地图" :visible.sync="mapVisible" :v-if="mapVisible" width="60%" @close="closeHandle" :append-to-body="true">
      <div id="mapCon"></div>
      <div class="marker"></div>
    </el-dialog>
    <!-- 地图弹框 -->

  </div>
</template>
<script>
import collectApi from '@/api/collect'
import { transformData } from '@/common/map_utils/json_util.js'

//地图相关
var map=null;
var vectorLayer=null;

export default {
  data() {
    return {
      tk: "fb3eec44ed909be3536962ff90220975", // 天地图密钥 fb3eec44ed909be3536962ff90220975 2329c6061242b26cba5d2d9b4da9a776
      userCollectId: [],//用户景点收藏id列表
      tableCollectId: [],//当前页显示的景点的id
      totalSize: 0,//总共有多少页
      pageNum: 1,//页码
      pageSize: 4,//每页几个景点
      popVisible: false,//操作栏是否可见
      tableCollect: [],//当前页面的景点
      tableLoading: false,//加载中
      mapVisible: false,//显示地图对话框
      scenaryName: '',
      position_x: 0,
      position_y: 0,
      refresh: false,
    }
  },
  methods: {
    async getUserCollect() {
      let res=await collectApi.getUserCollect(0);
      const id_list=[]
      res.data.forEach(item => {
        id_list.push(item.topic_id)
      })
      this.userCollectId=id_list
      this.totalSize=this.userCollectId.length;
      if(this.totalSize!=0)this.searchSite();
    },

    searchSite() {
      this.tableLoading=true;
      var queryStruct=new Zondy.Service.QueryFeatureStruct()
      queryStruct.IncludeAttribute=true
      var queryParam=new Zondy.Service.QueryByLayerParameter("gdbp://MapGisLocal/itravel/sfcls/全国景区",{
        resultFormat: 'json',
        struct: queryStruct,
      });
      //查询分页号
      queryParam.pageIndex=0;
      //设置查询要素数目
      queryParam.recordNumber=this.pageSize;

      //查询选项
      this.tableCollectId=this.userCollectId.slice((this.pageNum-1)*this.pageSize,this.pageNum*this.pageSize)
      var region_option="";
      for(var i=0,len=this.tableCollectId.length;i<len;++i) {
        if(i==0) region_option+="id = '"+this.tableCollectId[i]+"'";
        else region_option+="or id = '"+this.tableCollectId[i]+"'";
      }
      //属性查询
      queryParam.where=region_option

      var queryService=new Zondy.Service.QueryLayerFeature(queryParam,{
        ip: window.server.GIS_IP,
        port: window.server.GIS_PORT, //访问IGServer的端口号，.net版为6163，Java版为8089
      })
      //执行查询操作，querySuccess为查询回调函数
      queryService.query(this.querySuccess,this.queryError)
    },

    queryError(e) {
      console.log(e);
    },

    querySuccess(result) {
      this.tableLoading=false;
      if(result.length==0) {
        this.tableCollect=[]
        return;
      }
      var data=transformData(result);
      this.tableCollect=data;
      if(this.refresh) {
        let query={ path: "/personal/collection/scenicCollection" }
        query.pageNum=this.pageNum
        this.$router.push({
          path: '/goto',
          query: query
        })
      }
    },

    handleCurrentChange(val) {
      this.pageNum=val
      this.tableCollectId=this.userCollectId.slice((val-1)*this.pageSize,val*this.pageSize)
      this.searchSite()
    },

    async deleteSceneryCollect(item) {
      collectApi.changeCollect(item.id,0)
      await this.getUserCollect();
      this.refresh=true
    },

    toDetail(item) {
      //地图中心点
      this.scenaryName=item.name
      this.position_x=parseFloat(item.longitude)
      this.position_y=parseFloat(item.latitude)
      const center=ol.proj.fromLonLat([this.position_x,this.position_y])
      this.mapVisible=true
      // 后加载地图
      setTimeout(() => {
        this.initMap();
        map.getView().setCenter(center)
        this.createIconFeature(center)
      },0);

    },

    initMap() {
      this.initMapCon();
    },

    initMapCon() {
      if(!map) {
        map=new ol.Map({
          target: "mapCon",
          view: new ol.View({
            projection: ol.proj.get("EPSG:3857"), //默认为 3857
            center: ol.proj.fromLonLat([this.position_x,this.position_y]),
            minZoom: 10,
            zoom: 12,
          }),
          layers: [
            new ol.layer.Tile({
              name: "天地图矢量层",
              source: new ol.source.XYZ({
                url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk="+this.tk,
                wrapX: false,
              })
            }),
            new ol.layer.Tile({
              name: "矢量标注层",
              source: new ol.source.XYZ({
                url: "http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk="+this.tk,
                wrapX: false,
              })
            })
          ]
        });
      }
    },

    createIconFeature(center) {
      var iconFeature=new ol.Feature({
        geometry: new ol.geom.Point(center),
      });
      iconFeature.setStyle(this.createLabelStyle(iconFeature));
      var vectorSource=new ol.source.Vector({
        features: [iconFeature]
      });
      vectorLayer=new ol.layer.Vector({
        source: vectorSource
      });
      map.addLayer(vectorLayer)
    },

    createLabelStyle(feature) {
      return new ol.style.Style({
        image: new ol.style.Icon(({
          anchor: [0.5,46],
          anchorXUnits: 'fraction',
          anchorYUnits: 'pixels',
          scale: 1,
          src: require('../../../assets/marker/site.png')
        })),
        text: new ol.style.Text({
          //位置
          offsetY: 4,
          textAlign: 'center',
          //基准线
          textBaseline: 'middle',
          //文字样式
          font: 'bold 15px 微软雅黑',
          text: this.scenaryName,
          fill: new ol.style.Fill({ color: '#223458' }),
          stroke: new ol.style.Stroke({ color: '#EBEBEB',width: 2 })
        })
      })
    },

    closeHandle() {
      map.removeLayer(vectorLayer)
    },
  },
  mounted() {
    this.pageNum=this.$route.query.pageNum? this.$route.query.pageNum:1
    this.getUserCollect();

  }
}
</script>

<style scoped lang='scss'>
#title {
  visibility: hidden;
}

.content {
  height: 728px;
  padding: 60px 0;
  background-color: rgba(34, 52, 87, 0.6);
}

#scenery-list {
  height: 550px;
  width: 1000px;
  padding: 16px 32px;
  background-color: rgba(34, 52, 87, 0.3);
  border-radius: 8px;
  user-select: none;
  cursor: pointer;
  margin: auto;
}

.scenery_item {
  position: relative;
  height: 120px;
  padding: 16px 20px 0;
  font-family: -apple-system, system-ui, Segoe UI, Roboto, Ubuntu, Cantarell,
    Noto Sans, sans-serif, BlinkMacSystemFont, Helvetica Neue, PingFang SC,
    Hiragino Sans GB, Microsoft YaHei, Arial !important;

  .title {
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    margin-bottom: 4px;
    font-weight: 500;
    font-size: 22px;
    line-height: 33px;
    letter-spacing: 1.5px;
    color: rgba(26, 143, 204, 1);
  }

  .abstract {
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    font-weight: 400;
    font-size: 18px;
    line-height: 30px;
    color: #b0c4de;
  }

  .info {
    font-weight: 400;
    font-size: 18px;
    line-height: 27px;
    color: #b0c4de;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    padding-bottom: 12px;
    border-bottom: 1px solid rgba(228, 230, 235, 0.5);

    .user-name {
      color: #5fa6c3;
    }

    .footer-divider {
      display: inline-block;
      width: 1px;
      height: 12px;
      background-color: #e4e6eb;
      margin: 4px 8px 0 8px;
    }

    .like {
      margin-left: 4px;
    }

    .collect {
      margin-left: 4px;
    }

    .subject {
      float: right;
      color: rgba(209, 215, 221, 0.8);
      letter-spacing: 1px;
      background-color: rgba(0, 151, 215, 0.8);
      padding: 0 6px;
      margin-top: 2px;
      border-radius: 2px;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      font-size: 14px;
      min-height: 21px;
      line-height: 21px;
    }
  }

  .cover {
    position: absolute;
    top: 16px;
    right: 20px;

    img {
      display: inline;
      flex: 0 0 auto;
      width: 114px;
      height: 90px;
      margin-left: 24px;
      background-color: #fff;
      border-radius: 4px;
      border: 1px solid rgba(26, 160, 221, 0.5);
      overflow-clip-margin: content-box;
      overflow: clip;
      -o-object-fit: cover;
      object-fit: cover;
    }
  }
}

.with_cover {
  .title,
  .abstract,
  .info {
    padding-right: 160px !important;
  }
}

::v-deep .el-pagination {
  position: fixed;
  right: 24%;
  bottom: 8%;
}
</style>